<template>
  <div class="year-range-picker">
    <el-date-picker style="width: 90px" :clearable="false" v-model="startYear" type="year" placeholder="开始年份" format="YYYY" value-format="YYYY" class="year-picker" @change="changeStartYear">
    </el-date-picker>
    <span class="range-word"> 至 </span>
    <el-date-picker style="width: 90px" :clearable="false" v-model="endYear" type="year" placeholder="结束年份" format="YYYY" value-format="YYYY" class="year-picker" @change="changeEndYear">
    </el-date-picker>
  </div>
</template>
<script>
export default {
  name: 'YearRangePicker',
  // 接收父组件传入的数据
  props: {
    yearRange: {
      type: Array,
      required: false
    }
  },
  data() {
    return {
      startYear: '',
      endYear: ''
    };
  },
  mounted() {
    // 初始化自身变量
    this.startYear = this.yearRange[0] ? String(this.yearRange[0]) : '';
    this.endYear = this.yearRange[1] ? String(this.yearRange[1]) : '';
  },
  methods: {
    changeStartYear(val) {
      // 开始年份大于结束年份，调换
      if (this.endYear) {
        if (Number(this.startYear) > Number(this.endYear)) {
          this.startYear = this.endYear;
          this.endYear = val;
        }
      }
      // 将改动传回父组件
      this.$emit('yearChanged', [Number(this.startYear), Number(this.endYear)]);
    },
    changeEndYear(val) {
      if (this.startYear) {
        if (Number(this.startYear) > Number(this.endYear)) {
          this.endYear = this.startYear;
          this.startYear = val;
        }
      }
      this.$emit('yearChanged', [Number(this.startYear), Number(this.endYear)]);
    }
  }
};
</script>


<style lang="less" scoped>
.year-range-picker {
  color: black;
  text-align: center;
  font-size: 18px;
  height: 32px;
}

.range-word {
  display: inline-block;
  width: 32px;
  height: 32px;
  background: #e2e2e2;
  border: 1px solid #e2e2e2;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: #252b46;
  text-align: center;
  font-style: normal;
}
::v-deep .year-picker {
  width: 154px;
}
</style>
